#!/usr/bin/env python3
"""
Script to check for unclosed itemize environments in LaTeX files.
This is causing progressive indentation in the document.
"""
import os
import re
import glob

def check_itemize_balance(filepath):
    """Check if itemize environments are properly balanced in a file."""
    with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
        content = f.read()
    
    # Find all begin and end itemize commands
    begins = re.findall(r'\\begin\{itemize\}', content)
    ends = re.findall(r'\\end\{itemize\}', content)
    
    balance = len(begins) - len(ends)
    
    # Also check line by line for detailed analysis
    lines = content.split('\n')
    line_balance = 0
    max_nesting = 0
    problem_lines = []
    
    for i, line in enumerate(lines, 1):
        begins_in_line = len(re.findall(r'\\begin\{itemize\}', line))
        ends_in_line = len(re.findall(r'\\end\{itemize\}', line))
        
        line_balance += begins_in_line - ends_in_line
        max_nesting = max(max_nesting, line_balance)
        
        if line_balance < 0:  # More ends than begins at this point
            problem_lines.append((i, line.strip(), line_balance))
    
    return {
        'file': filepath,
        'total_begins': len(begins),
        'total_ends': len(ends),
        'balance': balance,
        'max_nesting': max_nesting,
        'final_balance': line_balance,
        'problem_lines': problem_lines
    }

def main():
    # Check all .tex files in the latex directory
    tex_files = glob.glob('part*/*.tex', recursive=True)
    tex_files.sort()
    
    total_imbalance = 0
    problematic_files = []
    
    print("=" * 80)
    print("LaTeX Itemize Environment Balance Analysis")
    print("=" * 80)
    
    for tex_file in tex_files:
        if os.path.exists(tex_file):
            result = check_itemize_balance(tex_file)
            
            if result['balance'] != 0:
                problematic_files.append(result)
                total_imbalance += result['balance']
                print(f"\n⚠️  IMBALANCE in {result['file']}:")
                print(f"   Begins: {result['total_begins']}, Ends: {result['total_ends']}")
                print(f"   Balance: {result['balance']:+d} (positive = unclosed)")
                print(f"   Max nesting: {result['max_nesting']}")
                
                if result['problem_lines']:
                    print(f"   Problem lines:")
                    for line_num, line_content, balance in result['problem_lines']:
                        print(f"      Line {line_num}: balance={balance:+d} | {line_content}")
            else:
                print(f"✓ {result['file']} - OK (begins: {result['total_begins']}, ends: {result['total_ends']})")
    
    print("\n" + "=" * 80)
    print(f"SUMMARY:")
    print(f"Total files checked: {len(tex_files)}")
    print(f"Files with imbalances: {len(problematic_files)}")
    print(f"Total cumulative imbalance: {total_imbalance:+d}")
    
    if total_imbalance > 0:
        print(f"\n🔥 CRITICAL: {total_imbalance} unclosed \\begin{{itemize}} environments!")
        print("This explains the progressive left indentation in later chapters.")
    elif total_imbalance < 0:
        print(f"\n🔥 CRITICAL: {abs(total_imbalance)} extra \\end{{itemize}} commands!")
    else:
        print(f"\n✅ All itemize environments are balanced.")
    
    print("=" * 80)

if __name__ == "__main__":
    main()